import re
from datetime import datetime, timedelta


def split_long(file_path):
    with open(file_path, 'r', encoding='utf-8') as srt_file:
        lines = srt_file.readlines()

    new_lines = []  # 保存时间戳和字幕，后面可用它来重新生成 序号
    current_time = ""

    for line in lines:
        line = line.strip()
        if line.isdigit():
            continue
        elif '-->' in line:
            current_time = line
        elif line != '':
            words = re.findall(r'\b\w+\b', line)  # Splitting line into words
            if len(words) > 13:
                # 计算时间分割的次数
                n = int(len(words) / 10) + 1
                time_group = split_timestamp_interval(current_time, n)
                # print(time_group)
                # 分割句子的同时把添加上
                time_index = 0
                for i in range(0, len(words), 10):
                    # 添加时间
                    new_lines.append(time_group[time_index])
                    time_index += 1

                    # 添加换行的功能
                    # new_line = ' '.join(words[i:i+5])
                    # # 如果后面的单词超过5个
                    # if i + 5 < len(words):
                    #     new_line += "\n"
                    # new_line += ' '.join(words[i+5:i+10])

                    new_line = ' '.join(words[i:i + 10])  # Combining words in groups of 10
                    new_lines.append(new_line + "\n")
            # 添加换行的功能
            # elif len(words) >= 10:
            #     new_lines.append(current_time)
            #     for i in range(0, len(words), 10):
            #         line = ' '.join(words[i:i+5])
            #         line += "\n"
            #         line += ' '.join(words[i+5:i+10])
            #     new_lines.append(line + "\n")
            else:
                new_lines.append(current_time)
                new_lines.append(line + "\n")

    new_lines_with_numbers = []
    # 遍历 new_lines 中的每一行
    num_index = 1
    for idx, line in enumerate(new_lines, start=1):  # start=1 使得 idx 从 1 开始
        if "-->" in line:
            # 插入序号化的字符串到 new_lines_with_numbers 中
            new_lines_with_numbers.append(f"{num_index}")
            new_lines_with_numbers.append(f"{line}")
            num_index += 1
        else:
            # 否则，直接添加原始字符串
            new_lines_with_numbers.append(line)

    # Writing to a new srt file
    with open(file_path, 'w', encoding='utf-8') as new_srt_file:
        new_srt_file.write('\n'.join(new_lines_with_numbers))


def split_timestamp_interval(interval_str, n):
    # 将毫秒部分的逗号替换为点
    interval_str = interval_str.replace(',', '.')

    # 解析时间区间字符串，假设格式为 "HH:MM:SS.fff --> HH:MM:SS.fff"
    start_end = interval_str.split(" --> ")
    start_time_str, end_time_str = start_end

    # 将字符串格式的时间戳转换为datetime对象，注意%f用于毫秒
    start_time = datetime.strptime(start_time_str, "%H:%M:%S.%f")
    end_time = datetime.strptime(end_time_str, "%H:%M:%S.%f")

    # 计算时间差
    time_diff = end_time - start_time

    # 如果n大于时间差的总秒数，则无法进行分割
    # if time_diff.total_seconds() < n:
    #     raise ValueError("The number of splits (n) is greater than the duration of the interval.")

    # 计算每个等分的时间间隔，这里使用总秒数进行计算以确保精度
    interval_seconds = time_diff.total_seconds() / n
    delta = timedelta(seconds=interval_seconds)

    # 输出等分的时间戳区间
    current_time = start_time
    result = []
    for _ in range(n - 1):  # 减1是因为我们不需要添加结束时间到列表中
        next_time = current_time + delta
        # 格式化输出，包含毫秒部分
        result.append(f"{current_time.strftime('%H:%M:%S.%f')[:-3]} --> {next_time.strftime('%H:%M:%S.%f')[:-3]}")
        current_time = next_time

    # 添加最后一个区间，确保包含结束时间
    result.append(f"{result[-1].split(' --> ')[1]} --> {end_time.strftime('%H:%M:%S.%f')[:-3]}")

    return result

# Example usage:
# split("19_当前时间轴_en-US.srt")

# def split(file_path):
#     with open(f'{file_path}', 'r', encoding='utf-8') as srt_file:
#         lines = srt_file.readlines()
#
#     for line in lines:
#         line = line.strip()
#         if line.isdigit():
#             continue
#         elif '-->' in line:
#             continue
#         elif line != '':
#
# split("19_当前时间轴_en-US.srt")

# 写一个python代码，能够针对srt字幕文件 拆分长句，使每句字幕最多10个单词，同时时间戳也要跟着拆分，并生成新的srt文件

# 拆分句子
# 先统计句子的单词个数，如果单词数大于13 就除以10，舍去余数，如果能整除，就要把结果res减 1，res是断句的次数
# 并计算 end_time-start_time 除以 res+1，得到结果res2,
# 然后start_time+res2
